package com.dp.utils;

import cn.hutool.core.util.BooleanUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;

import static com.dp.utils.RedisConstants.*;

@Component
public class CacheClient {
    private final StringRedisTemplate stringRedisTemplate;

    public CacheClient(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    public  void  set(String key, Object value, Long time , TimeUnit util){
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(value),time,util);
    }

    public  void  setWithLogicalExpire(String key, Object value, Long time , TimeUnit util){
        //设置逻辑过期
        RedisData redisData=new RedisData();
        redisData.setData(value);
        redisData.setExpireTime(LocalDateTime.now().plusSeconds(util.toSeconds(time)));
        stringRedisTemplate.opsForValue().set(key, JSONUtil.toJsonStr(redisData));
    }

    public <R,ID> R queryWithPassThrough(
            String keyPrefix, ID id, Class<R> type, Function<ID,R> dbFallBack, Long time , TimeUnit util){
        //从redis查询商铺缓存
        String key =keyPrefix+ id;
        String Json = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if(StrUtil.isNotBlank(Json)){
            //存在直接返回
            return JSONUtil.toBean(Json, type);
        }
        //判断是否为空值
        if (Json!=null) {
            return null;
        }
        //不存在，根据id查询数据库
        R r = dbFallBack.apply(id);
        if (r == null) {
            //不存在，返回错误
            //将空值写入redis
            stringRedisTemplate.opsForValue().set(key,"",CACHE_NULL_TTL,TimeUnit.MINUTES);
            return null;
        }
        //存在，缓存到redis并返回
//        stringRedisTemplate.opsForValue().set(key,JSONUtil.toJsonStr(r),time,util);
        //设置超时时间
//        stringRedisTemplate.expire(key,CACHE_SHOP_TTL, TimeUnit.MINUTES);
        this.set(key,r,time,util);
        return r;
    }


    public static final ExecutorService CACHE_REBUILD_EXECUTOR = Executors.newFixedThreadPool(10);
    public <R,ID> R queryWithLogicalExpire(
            String KeyPrefix ,ID id, Class<R> type, Function<ID,R> dbFallBack,Long time , TimeUnit util){
        //从redis查询商铺缓存
        String key =KeyPrefix+ id;
        String shopJson = stringRedisTemplate.opsForValue().get(key);
        //判断是否存在
        if(StrUtil.isBlank(shopJson)){
            //不存在直接返回
            return null;
        }
        //命中，需要先把json反序列化为对象
        RedisData redisData = JSONUtil.toBean(shopJson, RedisData.class);
        R r= JSONUtil.toBean((JSONObject) redisData.getData(), type);
        LocalDateTime expireTime = redisData.getExpireTime();
        //判断是否过期
        if (expireTime.isAfter(LocalDateTime.now() )){
            //未过期，直接返回店铺信息
            return r;
        }
        //已过期，需要缓存重建
        String LockKey=LOCK_SHOP_KEY+id;
        //先获取互斥锁
        boolean isLock = tryLock(LockKey);
        //判断是否获取锁成功
        if (isLock) {
            //获取成功，开启一个独立线程，实现缓存重建
            CACHE_REBUILD_EXECUTOR.submit(()->{
                try {
                    //先查询数据库
                    R r1 = dbFallBack.apply(id);
                    //再将数据写入redis
                    this.setWithLogicalExpire(key,r1,time,util);
//                    saveShop2Redis(id,20L);20L
                }catch (Exception e){
                    throw new RuntimeException(e);
                }finally {
                    //释放锁
                    unLock(LockKey);
                }
            });
        }
        //最后都要返回过期的店铺数据
        return r;
    }


    //尝试获取锁
    private boolean tryLock(String key){
        Boolean flag = stringRedisTemplate.opsForValue().setIfAbsent(key, "1", 10, TimeUnit.SECONDS);
        return BooleanUtil.isTrue(flag);
    }
    //释放锁
    private void unLock(String key){
        stringRedisTemplate.delete(key);
    }
}
